#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>

#ifndef MAX_MSGSIZE
#define MAX_MSGSIZE 1000
#endif

#define QLEN 10
#define LINELEN MAX_MSGSIZE
#define MAX(a,b) ((a)>(b)?(a):(b))

/* telnet localhost 1234 */

int
main (int argc, char *argv[])
{
	/* daytime should be int /etc/protocols */
  char *service = "1234";	/* service name or port number */
  char buf[LINELEN + 1];	/* buffer for one line of text */
  struct sockaddr_in fsin;	/* the request from address */
  int alen;			/* from-address length  */
  int tsock;			/* TCP master socket  */
  int usock;			/* UDP socket  */
  int nfds;
  fd_set rfds;			/* readable file descriptors */
  tsock = passiveTCP (service, QLEN);
  usock = passiveUDP (service);
  /* bit number of max fd */
  nfds = MAX (tsock, usock) + 1;
  FD_ZERO (&rfds);
  while (1)
    {
      FD_SET (tsock, &rfds);
      FD_SET (usock, &rfds);
      if (select
	  (nfds, &rfds, (fd_set *) 0, (fd_set *) 0, (struct timeval *) 0) < 0)
	printf ("select error: %s\n", strerror (errno));
      if (FD_ISSET (tsock, &rfds))
	{
	  /* TCP slave socket */
	  int ssock;
	  alen = sizeof (fsin);
	  ssock = accept (tsock, (struct sockaddr *) &fsin, &alen);
	  if (ssock < 0)
	    printf ("accept failed: %s\n", strerror (errno));
	  daytime (buf);
	  (void) write (ssock, buf, strlen (buf));
	  (void) close (ssock);
	}
      if (FD_ISSET (usock, &rfds))
	{
	  alen = sizeof (fsin);
	  if (recvfrom
	      (usock, buf, sizeof (buf), 0, (struct sockaddr *) &fsin,
	       &alen) < 0)
	    printf ("recvfrom: %s\n", strerror (errno));
	  daytime (buf);
	  (void) sendto (usock, buf, strlen (buf), 0,
			 (struct sockaddr *) &fsin, sizeof (fsin));
	}
    }
}
int
daytime (char buf[])
{
  char *ctime ();
  time_t now;
  (void) time (&now);
  sprintf (buf, "%s", ctime (&now));
}
